package com.panda.admin.login.authconfig;

import com.panda.admin.login.auth.detailsVo.SysUserDetails;
import com.panda.admin.constant.SecurityConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * author: tcy
 * createDate: 2022/10/26
 * description:Token增强器
 */
public class EnhanceTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();
        if (userAuthentication != null) {
            Object principal = userAuthentication.getPrincipal();
            SysUserDetails sysUserDetails = (SysUserDetails) principal;
            Map<String, Object> additionalInfo = new HashMap<>();

            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String grantType = request.getParameter("grant_type");

            additionalInfo.put(SecurityConstants.GRANT_TYPE_KEY,grantType);
            additionalInfo.put(SecurityConstants.DETAILS_USER_ID, sysUserDetails.getId());
            additionalInfo.put(SecurityConstants.DETAILS_USERNAME, sysUserDetails.getUsername());
            additionalInfo.put(SecurityConstants.DETAILS_NICKNAME, sysUserDetails.getNickName());
            additionalInfo.put(SecurityConstants.OPEN_ID, sysUserDetails.getOpenId());
            additionalInfo.put(SecurityConstants.ROLE_ID, sysUserDetails.getRoleId());
            additionalInfo.put(SecurityConstants.MOBILE, sysUserDetails.getMobile());
            additionalInfo.put(SecurityConstants.EMAIL, sysUserDetails.getEmail());
            additionalInfo.put(SecurityConstants.ICON_URL, sysUserDetails.getIconUrl());
            ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInfo);
        }
        return oAuth2AccessToken;
    }
}
